package com.mayikt.service;

import com.mayikt.service.classloader.MayiktClassloader;

/**
 * @ClassName Test003
 * @Author 蚂蚁课堂余胜军 QQ644064779 www.mayikt.com
 * @Version V1.0
 **/
public class Test003 {
    private static long startTime;

    public static void main(String[] args) throws ClassNotFoundException {
        MayiktClassloader mayiktClassloader =
                new MayiktClassloader("E:\\code\\OrderServiceImpl.class");
        Class<?> aClass = mayiktClassloader.loadClass("com.mayikt.service.impl.OrderServiceImpl");
        OrderService orderService = getOrderService(aClass);
        System.out.println(orderService.addOrder());
        startTime = mayiktClassloader.getLastModified();
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(3000);
                } catch (Exception e) {
                }
                long endTime = mayiktClassloader.getLastModified();
                if (endTime != startTime) {
                    System.out.println("文件发生变化..");
                    MayiktClassloader mayiktClassloader2 =
                            new MayiktClassloader("E:\\code\\OrderServiceImpl.class");
                    try {
                        Class<?> bClass = mayiktClassloader2.loadClass("com.mayikt.service.impl.OrderServiceImpl");
                        OrderService orderService2 = getOrderService(bClass);
                        System.out.println(orderService2.addOrder());
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    startTime = endTime;
                }
            }
        }).start();
    }

    public static OrderService getOrderService(Class<?> aClass) {
        try {
            return (OrderService) aClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}
